<script setup>
import TodoHeader from './components/todoHeader.vue'
import TodoMain from './components/todoMain.vue'
import TodoFooter from './components/todoFooter.vue'
import { computed, ref, watch } from 'vue'

// 提供数据
// const defatultValue = JSON.parse(localStorage.getItem('todos'))
const list = ref(JSON.parse(localStorage.getItem('todos')))
// const list = ref([
//   { id: 1, name: '吃饭', done: false },
//   { id: 2, name: '睡觉', done: true },
//   { id: 3, name: '打豆豆', done: false },
// ])
const type = ref('all')

// 切换是否完成
const changeDone = (id) => {
  // console.log(list.value)
  const todo = list.value.find((item) => item.id === id)
  todo.done = !todo.done
  // console.log(todo)
}

// 删除
const handleDel = (id) => {
  list.value = list.value.filter((item) => item.id !== id)
}

// 添加
const addTodo = (todoName) => {
  list.value.unshift({
    id: Date.now(),
    name: todoName,
    done: false,
  })
}

// 将所有的done 变成true
const checkAll = (flag) => {
  // console.log(flag)
  list.value.forEach((item) => (item.done = flag))
}

// 清除所有已经完成的todo
const clearFinish = () => {
  list.value = list.value.filter((item) => !item.done)
}
// 样式的选择
const chanegeTypeFn = (flag) => {
  type.value = flag
}

// 根据选择的 完成  未完成   已经完成   分别传递数据进行显示
const showList = computed(() => {
  if (type.value === 'all') {
    return list.value
  } else if (type.value === 'active') {
    return list.value.filter((item) => !item.done)
  } else {
    return list.value.filter((item) => item.done)
  }
})
// 监听所有的数据， 如果有数据改变了 就本地保存
watch(
  list,
  (value) => {
    localStorage.setItem('todos', JSON.stringify(value))
  },
  {
    deep: true,
    immediate: true,
  }
)
</script>
<template>
  <section class="todoapp">
    <TodoHeader @add-todo-fn="addTodo"></TodoHeader>
    <TodoMain
      :list="showList"
      @changeDone="changeDone"
      @handle-del="handleDel"
      @checkAllFn="checkAll"
    ></TodoMain>
    <TodoFooter
      :list="showList"
      @chanegeType="chanegeTypeFn"
      :type="type"
      @clran-fn="clearFinish"
    ></TodoFooter>
  </section>
</template>
<style></style>
